<template>
  <!-- 根据 formItem 的 mutable 属性判断是否显示开关组件，否则显示文本 -->
  <el-switch
    v-if="isMutable"
    v-bind="formItem.props"
    v-model="modelRef[formItem.key]"
  />
  <span v-else>{{ text }}</span>
</template>
<script setup lang="ts">
import { computed, defineProps, PropType, toRefs } from 'vue'
// 定义组件的 props
const props = defineProps({
  // 传递给表单的用户数据
  model: {
    type: Object as PropType<Record<string, any>>,
    default: () => ({})
  },
  // formItem 的表单配置
  formItem: {
    type: Object as PropType<{
      key: string;
      mutable?: boolean;
      props?: Record<string, any>;
    }>,
    default: () => ({})
  }
})
// 使用 toRefs 解构 props 中的 model，避免直接修改 props
const { model } = toRefs(props)
const modelRef: any = model
// 计算是否可编辑
const isMutable = computed(() =>
  props.formItem.mutable === undefined ? true : props.formItem.mutable
)
// 计算要显示的文本
const text = computed(() => {
  const isActive = modelRef.value[props.formItem.key]
  const activeText = props.formItem.props?.['active-text'] || '开启'
  const inactiveText = props.formItem.props?.['inactive-text'] || '关闭'
  return isActive ? activeText : inactiveText
})
</script>
